<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title></title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" type="text/css" href="https://www.layuicdn.com/layui-v2.5.5/css/layui.css" />
<style type="text/css">
.preview {
  width: 150px;
  height: 150px;
}
</style>
</head>

<body>
<form class="layui-form" action="" style="display: block;" id="form-data" lay-filter="data-form">
  <div class="layui-form-item">
    <label class="layui-form-label">修改头像</label>
    <div class="layui-input-inline">
      <div class="layui-upload-drag" id="img1">
        <i class="layui-icon"></i>
        <p>点击上传图片，或将图片拖拽到此处</p>
      </div>
    </div>
    <!--预览-->
    <div class="layui-input-inline">
      <div class="layui-upload-list">
        <img class="layui-upload-img preview" id="preview">
        <p id="previewText"></p>
      </div>
    </div>
  </div>
</form>
</body>
<script src="https://www.layuicdn.com/layui-v2.5.5/layui.js" type="text/javascript" charset="utf-8"></script>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/config.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
layui.use(["jquery", "upload", "form", "layer", "element"], function() {
  var $ = layui.$,
    element = layui.element,
    layer = layui.layer,
    upload = layui.upload,
    form = layui.form;
  //拖拽上传
  var uploadInst = upload.render({
    elem: '#img1',
    url: projectName + '/upload',
    before: function(obj) {
      //预读本地文件示例，不支持ie8
      obj.preview(function(index, file, result) {
        $('#preview').attr('src', result); //图片链接（base64）
      });
    },
    done: function(res) {
      //如果上传失败
      if(res.code > 0) {
        return layer.msg('上传失败');
      }
      //上传成功
      //打印后台传回的地址: 把地址放入一个隐藏的input中, 和表单一起提交到后台, 此处略..
      console.log(res.data.src);
      //window.parent.uploadHeadImage(res.data.src);
      var demoText = $('#previewText');
      demoText.html('<span style="color: #8f8f8f;">上传成功</span>');
    },
    error: function() {
      //演示失败状态，并实现重传
      var demoText = $('#demoText');
      demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
      demoText.find('.demo-reload').on('click', function() {
        uploadInst.upload();
      });
    }
  });
  element.init();
});
</script>

</html>